package com.msb.juc.c_020_01;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class T08_Semaphore_01 {
    volatile List list = new ArrayList();

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        T08_Semaphore_01 c = new T08_Semaphore_01();
        Semaphore s = new Semaphore(1);
        t1 = new Thread(() -> {
            try {
                s.acquire();
                for (int i = 0; i < 10; i++) {
                    c.add(new Object());
                    System.out.println("add " + i);
                    if (c.size() == 5) {
                        s.release();
                        try {
                            t2.start();
                            t2.join();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        s.acquire();
                    }
                }
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }, "t1");


        t2 = new Thread(() -> {
            try {
                s.acquire();
                System.out.println("t2 结束");
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2");

        t1.start();
    }
}
